#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2021/2/22 17:03
# @Author  : Wang Feng
# @FileName: taskplan.py.py
# @Software: PyCharm
import gzip
from io import StringIO

import apscheduler
from flask import Blueprint, jsonify, request
from networkx.classes import function

from app import scheduler
from app.ext import db
from app.models import TestScript
from app.utils.jenkins_excute import build_job
from app.utils.response_code import RET

taskplan = Blueprint('taskplan', __name__)


@taskplan.route('/get_jobs', methods=['GET'])
def get_jobs():
    """
    获取所有任务详情
    :return:
    """
    # apscheduler.job.Job
    # apscheduler.schedulers.background.BackgroundScheduler
    # print(1111)
    # print(scheduler.get_jobs())
    # print((scheduler.get_job('1')))
    # ret = db.session.execute(
    #     " select job_state  "
    #     " from  apscheduler_jobs "
    #     " where id = '{}'".format('1')
    #     )
    # a = ret.first()[0]
    # import chardet
    # ret = chardet.detect(a)
    # import pickle
    #
    # print(ret)
    # # print(pickle.load(a))
    # # print(str(a, encoding = "gbk")  )
    # print(str(pickle.loads(a)))
    # # data = gzip.decompress(a).decode("utf-8")
    # # print(str(a, encoding='utf-8'))
    # # print(2222)
    # # print(data)
    jobs_detail = []
    jobs = scheduler.get_jobs()
    # print(dir(jobs[0]))
    for job in jobs:
        # job_detail = {'id': job.id, 'name': job.name, 'func': job.func,
        #               'kwargs': job.kwargs, 'args': job.args, 'coalesce': job.coalesce,
        #               'executor': job.executor, 'func_ref': job.func_ref,
        #               'next_run_time': job.next_run_time, 'trigger': job.trigger}
        if isinstance(job.trigger, apscheduler.triggers.interval.IntervalTrigger):
            trigger = 'interval'
        elif isinstance(job.trigger, apscheduler.triggers.date.DateTrigger):
            trigger = 'date'
        elif isinstance(job.trigger, apscheduler.triggers.cron.CronTrigger):
            trigger = 'cron'
        else:
            trigger = None
        job_detail = {'id': job.id, 'name': job.name, 'func': job.func.__name__,
                      'kwargs': job.kwargs, 'args': job.args, 'coalesce': job.coalesce,
                      'executor': job.executor, 'func_ref': job.func_ref,
                      'next_run_time': None if job.next_run_time is None else job.next_run_time.strftime(
                          '%Y-%m-%d %H:%M:%S'),
                        'trigger': trigger
                      }
        # 'trigger': job.trigger.interval_length

        # print(dir(job.trigger))
        # print(job.trigger)
        # print(type(job.trigger))
        jobs_detail.append(job_detail)
        sorted_jobs_detail = sorted(jobs_detail, key=lambda x: int(x['id']), reverse=True)
    print(jobs_detail)

    # print(dir(jobs[0]))
    # print()

    return jsonify(code=RET.OK, msg='查询成功', total_page=1, count=len(jobs_detail), data=sorted_jobs_detail)


@taskplan.route('/add_job', methods=['POST'])
def add_job():
    print(request.json)
    task_name = request.json.get('name')
    tests = request.json.get('tests')
    print(tests)
    trigger = request.json.get('trigger')
    minutes = request.json.get('minutes')
    run_date = request.json.get('run_date')
    cron = request.json.get('cron')
    jobs = scheduler.get_jobs()
    test_list = []
    for test in tests:
        if len(test) == 4:
            test[3] += '.py'

        test_list.append('/'.join(test))
    tests_str = ' '.join(test_list)
    for job in jobs:
        if task_name == job.name:
            return jsonify(code=RET.DATAEXIST, msg='任务名称不能重复')
    try:
        import time
        t = time.time()
        task_id = str(round(t * 1000))
        if trigger == 'interval':
            ret = scheduler.add_job(id=task_id, name=task_name, func=build_job, args=(task_name, tests_str), trigger='interval',
                                    minutes=int(minutes),
                                    replace_existing=True)
        elif trigger == 'date':
            ret = scheduler.add_job(id=task_id, name=task_name, func=build_job, args=(task_name, tests),
                                    trigger='date',
                                    run_date=run_date,
                                    replace_existing=True)
        elif trigger == 'cron':
            ret = scheduler.add_job(id=task_id, name=task_name, func=build_job, args=(task_name, tests),
                                    trigger='cron',
                                    hour=cron['hour'],
                                    minute=cron['minute'],
                                    second=cron['second'],
                                    replace_existing=True)
        else:
            ret = None
        print(ret)
        if ret:
            return jsonify(code=RET.OK, msg='新增成功')
        else:
            return jsonify(code=RET.UNKOWNERR, msg='新增失败')
    except Exception as e:
        print(e)
        return jsonify(code=RET.UNKOWNERR, msg='新增失败')


@taskplan.route('/remove_job', methods=['GET'])
def remove_job():
    """移除任务"""
    job_id = request.args.get('id')
    scheduler.remove_job(str(job_id))
    return jsonify(code=RET.OK, msg='移除成功')


@taskplan.route('/pause_job', methods=['GET'])
def pause_job():
    """暂停任务"""
    job_id = request.args.get('id')
    scheduler.pause_job(str(job_id))
    return jsonify(code=RET.OK, msg='暂停成功')


@taskplan.route('/run_job', methods=['GET'])
def run_job():
    """执行任务"""
    job_id = request.args.get('id')
    scheduler.run_job(str(job_id))
    return jsonify(code=RET.OK, msg='操作成功')


@taskplan.route('/resume_job', methods=['GET'])
def resume_job():
    """恢复任务"""
    job_id = request.args.get('id')
    scheduler.resume_job(str(job_id))
    return jsonify(code=RET.OK, msg='恢复成功')


# @taskplan.route('/get_testscript', methods=['GET'])
# def get_testscript():
#     result = TestScript.query.filter().all()
#     scripts = []
#     for i in result:
#         script = {'epic': i.epic, 'feature': i.feature, 'story': i.story, 'title': i.title,
#                   'test_case_id': i.test_case_id}
#         scripts.append(script)
#     scripts_obj = []
#     for script in scripts:
#         b = {'epic': script['epic']}
#         feature_obj = []
#         if b not in scripts_obj:
#             scripts_obj.append(b)
#
#         # a.update(b)
#
#
#     print(scripts_obj)
#     return '1'

@taskplan.route('/get_epic', methods=['GET'])
def get_epic():
    # TestScript.query.filter()..all()
    result = TestScript.query.with_entities(TestScript.epic).distinct().all()
    epic_list = []
    for epic in result:
        epic_dic = {'label': epic[0], 'value': epic[0]}
        epic_list.append(epic_dic)
    return jsonify(code=RET.OK, data=epic_list, msg='查询成功')


@taskplan.route('/get_feature', methods=['GET'])
def get_feature():
    epic = request.args.get('epic')
    # TestScript.query.filter()..all()
    result = TestScript.query.filter_by(epic=epic).with_entities(TestScript.feature).distinct().all()
    feature_list = []
    for feature in result:
        feature_dic = {'label': feature[0], 'value': feature[0]}
        feature_list.append(feature_dic)
    return jsonify(code=RET.OK, data=feature_list, msg='查询成功')


@taskplan.route('/get_story', methods=['GET'])
def get_story():
    epic = request.args.get('epic')
    feature = request.args.get('feature')
    # TestScript.query.filter()..all()
    result = TestScript.query.filter_by(epic=epic, feature=feature).with_entities(TestScript.story).distinct().all()
    story_list = []
    for story in result:
        story_dic = {'label': story[0], 'value': story[0]}
        story_list.append(story_dic)
    return jsonify(code=RET.OK, data=story_list, msg='查询成功')


@taskplan.route('/get_testscript', methods=['GET'])
def get_testscript():
    epic = request.args.get('epic')
    feature = request.args.get('feature')
    story = request.args.get('story')
    # TestScript.query.filter()..all()
    result = TestScript.query.filter_by(epic=epic, feature=feature, story=story).with_entities(TestScript.test_case_id, TestScript.title).distinct().all()
    testscript_list = []
    for testscript in result:
        testscript_dic = {'label': testscript[1], 'value': testscript[0]}
        testscript_list.append(testscript_dic)
    return jsonify(code=RET.OK, data=testscript_list, msg='查询成功')
